<template>
  <view class="login" :style="pageHeight">
    <image :src="vuex_imgPath+'/login_bg.png'" class="login-bg" />
    <view class="login-int">
      <view class="t-int">手机号码</view>
      <view class="login-int-box">
        <u-input
          v-model="phone"
          :maxlength="11"
          placeholder="请输入手机号"
          font-size="28rpx"
          placeholder-style="color: #999;font-size:24rpx;"
        />
      </view>
    </view>
    <view class="login-int">
      <view class="t-int">验证码</view>
      <view class="login-int-box">
        <view class="verode-box">
          <u-input v-model="code" placeholder="短信验证码" font-size="28rpx" placeholder-style="color: #999;font-size:24rpx;" />
        </view>
        <view class="verode" @click="getCode()">{{ getCodeName }}</view>
      </view>
    </view>
    <view class="login-btn">
      <!-- #ifdef H5 -->
      <button type="default" :plain="true" class="login-box login-org btn-noborder login-org-curr" @click="Login">立即登录</button>
      <!-- #endif -->
      <!-- #ifdef MP-WEIXIN -->
      <button type="default" :plain="true" class="login-box login-org btn-noborder login-org-curr" @click="Login">登录/注册</button>
      <!-- #endif -->
      <!-- #ifdef MP-ALIPAY -->
      <button type="default" :plain="true" class="login-box login-org btn-noborder login-org-curr" @click="Login">登录/注册</button>
      <!-- #endif -->
    </view>
    <view class="privacy-radio">
      <u-checkbox-group v-model="flag" placement="row">
        <u-checkbox
          shape="circle"
          active-color="#FF5533"
          name="true"
        />
      </u-checkbox-group>
      <view class="radio-hint">
        若手机号未注册将进入注册流程，注册即为同意
        <view @click="goWeb('agree')">《鑫方盛平台服务协议》</view>和
        <view @click="goWeb('pol')">《鑫方盛隐私政策》</view>
      </view>
    </view>
    <!-- #ifdef H5 -->
    <view>
      <view>
        <!--组件-->
        <slideVerify v-if="slideShowStatus" @seccess="slideYzSeccess" />
      </view>
    </view>
    <!-- #endif -->
  </view>
</template>

<script>
import { getCode, codeLogin, traceless } from '@/api/login.js';
import { getLoginInfoFn, initSlide } from '@/common/common'
import '@/static/scss/login.scss';
import { getAuthCode } from '@/utils/login';
import slideVerify from '@/components/slide-verify.vue';

export default {
  name: 'Login',
  components: {
    slideVerify
  },
  data() {
    return {
      slideShowStatus: false,
      pageHeight: '',
      getCodeName: '获取验证码',
      codeFlag: true,
      phone: '',
      code: '',
      flag: false,
      type: '',
      callbackUrl: '',
      urlParams: '',
      registParams: '',
      clicktime: true,
      skuId:'',
      title:'',
      exchangeType:'',
    }
  },
  onShow() {
    // #ifdef MP-ALIPAY
    if (uni.getStorageSync('inviteCode')) {
      this.callbackUrl = '/shopIndex/shopIndex' //扫门店二维码注册跳转云采首页
      this.type = 'ground'
    }
    // #endif
    //#ifdef H5
    //initSlide()
    // #endif
  },
  onLoad(option) {
    const { type = '', callbackUrl = '', urlParams = '', registParams = '' } = option
    this.type = type
    this.callbackUrl = callbackUrl
    this.urlParams = urlParams == '' ? {} : JSON.parse(urlParams)
    this.registParams = registParams == '' ? {} : JSON.parse(registParams)
    if(this.type == 'pointsGoodsDetail'){
    this.skuId =this.urlParams.skuId
    this.title =this.urlParams.title
    this.exchangeType =this.urlParams.exchangeType
    }
    console.log('验证码登录', this.urlParams)
    // #ifdef MP-WEIXIN
    if (uni.getStorageSync('inviteCode')) {
      this.callbackUrl = '/shopIndex/shopIndex' //扫门店二维码注册跳转云采首页
      this.type = 'ground'
    }
    // #endif
  },
  methods: {
    setBackUrlFn() {
      /*根据账号类型跳转对应首页*/
      if (!this.callbackUrl && (!this.vuex_loginStatus || (this.vuex_loginStatus && this.vuex_memberInfo && (this.vuex_memberInfo.accountType == 20 || this.vuex_memberInfo.accountType == 30)))) {
        this.callbackUrl = '/shopIndex/shopIndex'
      } else {
        !this.callbackUrl ? this.callbackUrl = '/pages/index/index' : ''
      }
    },
    goWeb(type) {
      if (type == 'pol') {
        uni.navigateTo({ url: `./pol` })
      } else {
        uni.navigateTo({ url: `./agree` })
      }
    },
    phoneFun(phones) {
      var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!myreg.test(phones)) {
        return false
      } else {
        return true
      }
    },
    tranClassFn(parame) {
      traceless({ nvcVal: parame }).then((res) => {
        this.resultTrace(res);
      }).catch(() => {
        // eslint-disable-next-line no-mixed-spaces-and-tabs
      })
    },
    resultTrace(res) {
      if (res.data == 200 || res.data == 100) {
        //验证通过
        this.successCode()
        return;
      }

      if (res.data == 400) {
        //验证不通过
        var ncoption = {
          // 声明滑动验证需要渲染的目标ID。
          renderTo: 'nc',
        }
        // 唤醒二次验证（滑动验证码）
        window.nvc.getNC(ncoption);
        this.slideShowStatus = true
        return;
      }

      if (res.data == 900) {
        //二次验证验证不通过
        console.log('验证失败', 3000);
        return;
      }

      if (res.data == 800) {
        //直接拦截
        console.log('您的账号存在异常，请联系在线客服！', 3000);
        return;
      }
    },
    getCode() {
      const _this = this

      if (!this.phoneFun(this.phone)) {
        this.$u.toast('请输入正确的手机号')
        return
      }
      if (!this.codeFlag) return
      // #ifdef H5
      // window.nvc.getNVCValAsync(function(nvcVal) {
      //   console.log('点击获取验证码掉无痕')
      //   if (_this.slideShowStatus == true) {
      //     _this.slideShowStatus = false
      //   }
      //   _this.tranClassFn(decodeURIComponent(nvcVal))
      // });
      this.successCode()
      // #endif
      // #ifdef MP-ALIPAY || MP-WEIXIN
      this.successCode()
    // #endif
    },

    successCode() {
      let timer = null
      const params = { phoneNumber: this.phone }
      const that = this
      getCode(params).then((res) => {
        if (res.errorCode == 0) {
          timer = that.countDownFn(60)
          this.$u.toast(`短信验证码已发送至${this.phone}`)
        } else {
          clearInterval(timer)
          this.getCodeName = `获取验证码`
          this.codeFlag = true
          this.$u.toast(res.msg)
        }
      })
    },
    countDownFn(num) {
      const timer = setInterval(() => {
        if (num > 0) {
          num--
          this.getCodeName = `${num}秒后重新获取`
          this.codeFlag = false
        } else {
          clearInterval(timer)
          this.getCodeName = `获取验证码`
          this.codeFlag = true
        }
      }, 1000)
      return timer
    },
    Login() {
      console.log(this.registParams);
      if (!this.phoneFun(this.phone)) {
        this.$u.toast('请输入正确的手机号')
        return
      }
      if (!this.code) {
        this.$u.toast('验证码不能为空')
        return
      }
      if (!this.flag) {
        this.$u.toast('未勾选协议，请勾选')
        return
      }
      const provider = this.vuex_provider;
      getAuthCode(provider, (loginRes) => {
        if (loginRes.code) {
          this.$u.vuex('vuex_login_code', loginRes.code)
        }
      })
      let registParams = {}
      registParams = (this.registParams && Object.keys(this.registParams).length > 0) ? this.registParams : this.vuex_sharePushmanCompanyInfo
      const { branchId = '', branchName = '', settleType } = registParams || {}
      const params = {
        phoneNumber: this.phone,
        verificationCode: this.code,
        inviteCode: uni.getStorageSync('inviteCode'),
        memberAscriptionId: branchId,
        memberAscriptionName: branchName,
        settleType: settleType || null,
        appFlag: 0, // "小程序和M站区分[0-小程序 1-M站]
        // #ifdef MP-ALIPAY
        appType: 3, //"应用类型1:微信app 2:微信小程序 3:支付宝小程序"
        // #endif
        // #ifdef MP-WEIXIN
        appType: 2,
        // #endif
      }
      if (this.vuex_mapAddress) {
        // 小程序新增登录/注册所在地信息
        const { provinceName, cityName, districtName } = this.vuex_mapAddress
        params.commonParamProvinceName = provinceName
        params.commonParamCityName = cityName
        params.commonParamDistrictName = districtName
      }
      codeLogin(params).then((res) => {
        if (res.errorCode == 0) {
          this.$u.vuex('vuex_accountInfo', res.data) //res.data
          this.$u.vuex('vuex_userInfo', res)
          getLoginInfoFn(res.data.memberId)
          this.$u.vuex('vuex_loginStatus', true)
          let paramStr = ''
          if (this.urlParams) {
            for (const urlParamsKey in this.urlParams) {
              paramStr += urlParamsKey + '=' + this.urlParams[urlParamsKey] + '&'
            }
          }
          this.setBackUrlFn()
          if (this.type == 'order') {
            uni.reLaunch({ url: this.callbackUrl })
          } else if (this.type == 'my') {
            uni.reLaunch({ url: this.callbackUrl })
          } else if (this.type == 'ground') {
            uni.reLaunch({ url: this.callbackUrl })
          }else if(this.type == 'pointsGoodsDetail'){
          uni.reLaunch({ url: '/myAccount/pointsMall/pointsGoodsDetail?skuId='+this.skuId+'&title=' + this.title + '&exchangeType=' +this.exchangeType})
        
          } else {
               console.log('验证码登录接参', this.urlParams)
            uni.reLaunch({ url: this.callbackUrl + '?' + paramStr })
          }
        } else {
          this.$u.toast(res.msg)
        }
      })
    },
    //接无痕验证收验证成功的值
    slideYzSeccess(data) {
      console.log('400时出现的滑块 当移动滑块成功之后返回')
      //会话ID（sessionId）、签名串（sig）、请求唯一标识（token）
      console.log(data.sessionId)
      console.log(data.sig)
      console.log(data.token)
      this.Login()
    },
  }
}
</script>

<style scoped lang="scss">
.login{
  padding-top: 50rpx;
}
.login-int-box {
  border: 2rpx solid $uni-grey-e2 !important;
  // #ifdef MP-ALIPAY
  /deep/ .u-input{
    padding-top: 8rpx!important;
  }
  // #endif
  /deep/ input {
    height:48rpx!important;
    line-height:48rpx!important;
  }
}
</style>
